﻿using System.Collections.ObjectModel;
using System.ComponentModel;

namespace Redbrick.Silverlight.Common
{
	public class NotifyCollection<_type> : ObservableCollection<_type>
	{
        private void NotifyCollection_PropertyChanged(object sender, PropertyChangedEventArgs args)
        {
            base.OnPropertyChanged(args);
        }

		private void AttachHandler(_type item)
		{
			if (item is INotifyPropertyChanged)
				((INotifyPropertyChanged)item).PropertyChanged += new PropertyChangedEventHandler(this.NotifyCollection_PropertyChanged);

		}
		private void DettachHandler(_type item)
		{
			if (item is INotifyPropertyChanged)
				((INotifyPropertyChanged)item).PropertyChanged -= new PropertyChangedEventHandler(NotifyCollection_PropertyChanged);

		}

		protected override void InsertItem(int index, _type item)
		{
			AttachHandler(item);
				
			
			base.InsertItem(index, item);
		}

		protected override void RemoveItem(int index)
		{
			this.DettachHandler(this.Items[index]);
			base.RemoveItem(index);
		}
		protected override void SetItem(int index, _type item)
		{
			this.AttachHandler(item);
			base.SetItem(index, item);
		}
		
	}
}
